package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsMchntBaseInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.MchntAcctDetailMapper;
import cc.rengu.igas.bsps.common.dao.TradeDetailInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBaseInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.MchntAcctDetailMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.TradeDetailInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.BspsMchntAcctDetail;
import cc.rengu.igas.bsps.common.entity.MchntBaseInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.bean.MchntRealAcctDetailBean;
import cc.rengu.igas.bsps.facade.request.RealAcctDetailInfoQueryRequest;
import cc.rengu.igas.bsps.facade.response.RealAcctDetailInfoQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.SrcTxnAuthCfgMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SrcTxnAuthCfgMapperImpl;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.OtherBizInfo;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.entity.SrcTxnAuthCfg;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.RiskMonitorInfo;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 实时入账明细查询
 */
public class RealAcctDetailInfoQueryService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        RealAcctDetailInfoQueryRequest realAcctDetailInfoQueryRequest = new RealAcctDetailInfoQueryRequest();
        // 读取存在xml树里的实体类
        ConvertUtil.convertOutput(realAcctDetailInfoQueryRequest);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.FRONT_SEQ_NUM, realAcctDetailInfoQueryRequest.getHeader().getTraceNo());
        return realAcctDetailInfoQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        RealAcctDetailInfoQueryRequest realAcctDetailInfoQueryRequest = (RealAcctDetailInfoQueryRequest) request;
        String instId = realAcctDetailInfoQueryRequest.getHeader().getInstId();
        String mchntNo = realAcctDetailInfoQueryRequest.getMchntNo();
        String startDate = realAcctDetailInfoQueryRequest.getStartDate();
        String endDate = realAcctDetailInfoQueryRequest.getEndDate();
        String pageIndex = realAcctDetailInfoQueryRequest.getPageIndex();
        String pageSize = realAcctDetailInfoQueryRequest.getPageSize();

        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(startDate) || StringUtil.isEmptyOrNull(endDate) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(pageIndex) || StringUtil.isEmptyOrNull(pageSize)) {
            rglog.error("必填性校验失败!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*查询商户*/
        BspsMchntBaseInfoMapper mchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(instId, mchntNo);
        if (mchntBaseInfo == null) {
            rglog.info("获取商户信息失败！");
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        /*分页*/
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(Integer.parseInt(pageIndex));
        pageInfo.setPageSize(Integer.parseInt(pageSize));
        /*查询入账明细*/
        MchntAcctDetailMapper mchntAcctDetailMapper = new MchntAcctDetailMapperImpl();
        PageResult pageResult = mchntAcctDetailMapper.selectMchntAcctDetailInfoBySettleDateAndMchntNoAndInstId(instId, mchntNo, startDate, endDate, pageInfo);
        if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
            rglog.error("未查到入账明细,机构号<{}>，商户号<{}>!", instId, mchntNo);
            //throw new BizException(RespCodeEnum.MCHNT_ACCT_DETAIL_EMPTY.getRespCode(), RespCodeEnum.MCHNT_ACCT_DETAIL_EMPTY.getRespDesc());
        }
        List<BspsMchntAcctDetail> bspsMchntAcctDetailList = new ArrayList<>();
        RealAcctDetailInfoQueryResponse realAcctDetailInfoQueryResponse = new RealAcctDetailInfoQueryResponse();
        /* 根据取出记录条数做对应处理 */
        if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult()) {
            rglog.info("根据查询条件查询到0条入账明细!");
            realAcctDetailInfoQueryResponse.setTotalPage("0");
            realAcctDetailInfoQueryResponse.setTotalRows("0");
        } else {

            for (Object object : pageResult.getResult()) {
                BspsMchntAcctDetail bspsMchntAcctDetail = new BspsMchntAcctDetail();
                BeanUtil.beanCopy(object, bspsMchntAcctDetail);
                bspsMchntAcctDetailList.add(bspsMchntAcctDetail);
            }
            List<MchntRealAcctDetailBean> mchntRealAcctDetailBeanList = new ArrayList<MchntRealAcctDetailBean>();
            //BeanUtil.beanCopy(bspsMchntAcctDetailList,mchntRealAcctDetailBean);
            rglog.info("SIZE=<{}>", pageResult.getResult().size());
            /*查询支付订单表*/
            for (int i = 0; i < bspsMchntAcctDetailList.size(); i++) {
                BspsMchntAcctDetail bspsMchntAcctDetail = bspsMchntAcctDetailList.get(i);
                String transSeqNum = bspsMchntAcctDetailList.get(i).getTransSeqNum();
                /*查询订单list*/
                TradeDetailInfoMapper tradeDetailInfoMapper = new TradeDetailInfoMapperImpl();
                List<PayOrderInfo> payOrderInfoList = tradeDetailInfoMapper.bspsSelectPayOrderInfoBySysSeqNum(instId, transSeqNum);
                if (payOrderInfoList == null || payOrderInfoList.size() == 0) {
                    rglog.info("明细表有数据，支付表没有!");
                    throw new BizException(RespCodeEnum.GET_MCHNT_ORDER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_MCHNT_ORDER_INFO_ERROR.getRespDesc());
                }

                PayOrderInfo payOrderInfo = payOrderInfoList.get(0);
                //查询
                MchntOrderInfoMapper mchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
                MchntOrderInfo mchntOrderInfo = mchntOrderInfoMapper.selectMchntOrderInfoByPrimaryKey(instId, transSeqNum, payOrderInfo.getMchntNo());

                MchntRealAcctDetailBean mchntRealAcctDetailBean = new MchntRealAcctDetailBean();
                BeanUtil.beanCopy(bspsMchntAcctDetail, mchntRealAcctDetailBean);
                mchntRealAcctDetailBean.setTransAmt(bspsMchntAcctDetail.getTransAmt());
                mchntRealAcctDetailBean.setMchntNetAmt(bspsMchntAcctDetail.getMchntNetAmt());
                mchntRealAcctDetailBean.setMchntTotalFee(bspsMchntAcctDetail.getMchntTotalFee());
                mchntRealAcctDetailBean.setMchntActualFee(bspsMchntAcctDetail.getMchntActualFee());
                mchntRealAcctDetailBean.setMchntdiscountFee(bspsMchntAcctDetail.getMchntDiscountFee());
                mchntRealAcctDetailBean.setTxnNum(bspsMchntAcctDetail.getTxnNum());
                mchntRealAcctDetailBean.setTxnDate(bspsMchntAcctDetail.getTransDate());
                mchntRealAcctDetailBean.setTxnTime(bspsMchntAcctDetail.getTransTime());
                mchntRealAcctDetailBean.setPayType(payOrderInfo.getPayType());
                mchntRealAcctDetailBean.setMchntOrderId(payOrderInfo.getMchntOrderId());
                mchntRealAcctDetailBean.setSysSeqNum(bspsMchntAcctDetail.getTransSeqNum());
                mchntRealAcctDetailBean.setTransStatus(payOrderInfo.getTransStatus());
                if (mchntOrderInfo != null) {
                    mchntRealAcctDetailBean.setOrderDesc(mchntOrderInfo.getOrderDesc());
                }
                SrcTxnAuthCfgMapper srcTxnAuthCfgMapper = new SrcTxnAuthCfgMapperImpl();
                List<SrcTxnAuthCfg> srcTxnAuthCfgList = srcTxnAuthCfgMapper.selectSrcTxnAuthCfgInfo(payOrderInfo.getInstId(), payOrderInfo.getSysSeqNum().substring(0, 4));
                if (srcTxnAuthCfgList != null && !srcTxnAuthCfgList.isEmpty()) {
                    Optional<SrcTxnAuthCfg> srcTxnAuthCfgOpt = srcTxnAuthCfgList.stream().filter(item -> item.getTxnNum().equals(payOrderInfo.getTxnNum()) && item.getBizType().equals(payOrderInfo.getBizType())).findFirst();
                    srcTxnAuthCfgOpt.ifPresent(srcTxnAuthCfg -> mchntRealAcctDetailBean.setTxnName(srcTxnAuthCfg.getTxnName()));
                }

                /*查询收银员信息*/
                BspsUserInfoMapper BspsUserInfoMapper = new BspsUserInfoMapperImpl();
                UserInfo userInfo = BspsUserInfoMapper.selectBspsUserInfoByUserId(instId, bspsMchntAcctDetail.getUserId());
                if (userInfo != null) {
                    rglog.info("有收银员信息!");
                    /*throw new BizException(RespCodeEnum.GET_MCHNT_ORDER_INFO_ERROR.getRespCode(),RespCodeEnum.GET_MCHNT_ORDER_INFO_ERROR.getRespDesc());*/
                    mchntRealAcctDetailBean.setCashierId(userInfo.getUserId());
                    mchntRealAcctDetailBean.setUserName(userInfo.getNickName());
                    mchntRealAcctDetailBean.setPayerAcctInfo(payOrderInfo.getPayeeAcctInfo());
                }

                String otherBizInfoStr = bspsMchntAcctDetail.getOtherBizInfo();
                OtherBizInfo otherBizInfo = JSON.parseObject(otherBizInfoStr, OtherBizInfo.class);
                String acctBalance = "";
                if (otherBizInfo != null) {
                    for (int j = 0; j < otherBizInfo.getMchntOrderMainInfoList().size(); j++) {
                        MchntOrderInfo MchntOrderInfo = otherBizInfo.getMchntOrderMainInfoList().get(j);
                        if (MchntOrderInfo.getMchntNo().equals(mchntNo)) {
                            acctBalance = MchntOrderInfo.getVirtualAcctBalance();
                        }
                    }
                }
                mchntRealAcctDetailBean.setAcctBalance(acctBalance);   //虚拟账户余额
                mchntRealAcctDetailBeanList.add(mchntRealAcctDetailBean);
            }
            realAcctDetailInfoQueryResponse.setMchntRealAcctDetailBeanList(mchntRealAcctDetailBeanList);
            realAcctDetailInfoQueryResponse.setMchntNo(mchntBaseInfo.getMchntNo());
            realAcctDetailInfoQueryResponse.setMchntName(mchntBaseInfo.getMchntName());
            realAcctDetailInfoQueryResponse.setTotalPage(Integer.toString(pageResult.getPageInfo().getTotalPage()));
            realAcctDetailInfoQueryResponse.setTotalRows(Integer.toString(pageResult.getPageInfo().getTotalRows()));
            realAcctDetailInfoQueryResponse.setPageIndex(Integer.toString(pageResult.getPageInfo().getPageIndex()));
            realAcctDetailInfoQueryResponse.setPageSize(Integer.toString(pageResult.getPageInfo().getPageSize()));
        }

        BizResponse bizResponse = new BizResponse();
        bizResponse.setResult(realAcctDetailInfoQueryResponse);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        RealAcctDetailInfoQueryResponse realAcctDetailInfoQueryResponse = (RealAcctDetailInfoQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(realAcctDetailInfoQueryResponse);
    }

    @Override
    protected RiskMonitorInfo getRiskMonitorInfo() {
        return null;
    }

}
